﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using RTracker.Models.Common;
using RTracker.Models.User;
using RTracker.Models.ErrorLog;
using System.Security.Cryptography;
using System.Text;

namespace RTracker.Models.Login
{
    public class MLogin
    {

        /// <summary>
        ///  This function is used to validate user login credentials
        /// </summary>
        /// <returns>List of type COrganization</returns>
        public CStatus ValidateUser(CAuthenticationContext objCAuthenticationContext, ref CUser objCUser)
        {
            CStatus oCStatus = new CStatus();

            // computer password hash
            //objCUser.LogonPassword = ComputePasswordHash(objCUser); // working, tested
           
            try
            {
                string connectionstring = CCommonCollection.ConnectionString;
                SqlConnection con = new SqlConnection(connectionstring);
                SqlCommand cmd = new SqlCommand("r_validate_user_procedure", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add("@logon_name", SqlDbType.VarChar).Value = objCUser.LogonName;
                cmd.Parameters.Add("@logon_password", SqlDbType.VarChar).Value = objCUser.LogonPassword;
                cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                con.Open();
                
                cmd.ExecuteNonQuery();

                int nResult = int.Parse(cmd.Parameters["@idOut"].Value.ToString());

                con.Close();

                if(nResult > 0)
                {
                    objCUser.UserId = nResult;
                    objCUser.OrganizationId = int.Parse(cmd.Parameters["@error"].Value.ToString());
                    oCStatus.Success = true;
                    oCStatus.StatusDetails = CAppConstants.LoginSuccess;
                }
                else
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError(); //CAppConstants.Loginfailed;
                }

            }
            catch (Exception ex)
            {

                oCStatus.Success = false;
                oCStatus.StatusDetails = ex.Message;

            }
            return oCStatus;
        }
        /// <summary>
        /// To computer salted hash of the password entered by user
        /// </summary>
        /// <param name="objCUser">User details</param>
        /// <returns>salted password hash</returns>
        public static string ComputePasswordHash(CUser objCUser)
        {
            // to store password hash
            string base64PasswordHash = "";

            string strPassword = objCUser.LogonPassword;
            string strUsername = objCUser.LogonName;

            // generate salt for each user
            string strSalt = strPassword.Substring(0, 3) + strUsername.Substring(strUsername.Length - 3, 3);

            // generated salted password
            strPassword = strSalt + strPassword;

            // convert into bytearray for generating hash
            byte[] bytPassword = Encoding.UTF8.GetBytes(strPassword);

            HashAlgorithm hashAlgo = new SHA256CryptoServiceProvider();
            byte[] byteHash = hashAlgo.ComputeHash(bytPassword);

            base64PasswordHash = Convert.ToBase64String(byteHash);
            return base64PasswordHash;
        }
    }
}